import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { Select, Spin, message } from 'antd';
import { dynamicDictSelectData } from '@/services/prefiling/onlineCollecting';
import debounce from 'lodash/debounce';
import { DictionaryItem } from '@/types/prefiling/onlineCollecting';

interface DynamicDictSelectProps {
  field: {
    dictCode?: string;
    code: string;
    name: string;
    [key: string]: any;
  };
  commonProps: any;
  defaultValue: any;
  style?: React.CSSProperties;
  className?: string;
}

const DynamicDictSelect: React.FC<DynamicDictSelectProps> = ({
  field,
  commonProps,
  defaultValue,
  style,
  className
}) => {
  const [searchLoading, setSearchLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<DictionaryItem[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [selectedValue, setSelectedValue] = useState(defaultValue);

  // 搜索处理函数
  const handleSearch = useCallback(async (value: string) => {
    setInputValue(value);
    
    if (!value || !field.dictCode) {
      setSearchResults([]);
      return;
    }
    
    try {
      setSearchLoading(true);
      const res = await dynamicDictSelectData(field.dictCode, {
        inputValue: value 
      });
    
      if (res) {
        setSearchResults(res || []);
      } else {
        message.error(res?.message || '查询失败');
        setSearchResults([]);
      }
    } catch (error) {
      console.error('搜索失败:', error);
      message.error('搜索失败');
      setSearchResults([]);
    } finally {
      setSearchLoading(false);
    }
  }, [field.dictCode]);

  // 防抖处理
  const debouncedSearch = useMemo(() => {
    return debounce(handleSearch, 300);
  }, [handleSearch]);

  // 合并搜索结果和当前输入值（如果不在结果中）
  const mergedOptions = useMemo(() => {
    const options = [...searchResults];
    
    // 如果当前输入值不在搜索结果中，且不为空，则添加到选项中
    if (inputValue && !searchResults.some(item => item.name === inputValue)) {
      options.push({
        label: inputValue,
        name:inputValue,
        value: inputValue,
      });

    }
    console.log(options)
    return options;
  }, [searchResults, inputValue]);

  // 处理选择变化
  const handleChange = (value: string, option: any) => {
    setSelectedValue(value);
    
    // 如果选择了自定义输入的值，且这个值不在选项中，则添加到选项中
    if (value && !searchResults.some(item => item.name === value)) {
      setSearchResults(prev => [
        ...prev,
        {
          label: value,
          value: value,
        }
      ]);
    }
    
    // 调用原始onChange（如果有）
    if (commonProps.onChange) {
      commonProps.onChange(value, option);
    }
  };

  // 组件卸载时取消防抖
  useEffect(() => {
    return () => {
      debouncedSearch.cancel();
    };
  }, [debouncedSearch]);

  return (
    <Select
      {...commonProps}
      className={`dynamicDictSelect ${field.code} ${className || ''}`}
      style={{ width: '100%', ...style }}
      showSearch
      allowClear
      onSearch={debouncedSearch}
      onChange={handleChange}
      filterOption={false}
      mode="combobox"  
      optionFilterProp="children"
      notFoundContent={searchLoading ? <Spin size="small" /> : null}
      options={mergedOptions.map(item => ({
        value: item.name,
        label: item.name
      }))}
      value={selectedValue}
    />
  );
};

export default DynamicDictSelect;